package com.kgc.controller;

import com.alibaba.fastjson.JSON;
import com.kgc.bean.DiscountTrick;
import com.kgc.bean.User;
import com.kgc.config.annotation.RequestPermission;
import com.kgc.config.annotation.RequestUser;


import com.kgc.service.CouponService;
import com.kgc.util.RedisUtils;
import com.kgc.util.ResultBuildUtil;
import com.kgc.util.ReturnResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

//优惠券操作入口
@RestController
@Slf4j
@Api(tags = "优惠券操作入口")
public class CouponController {
    @Autowired
    private CouponService couponService;

    @Autowired
    private RedisUtils redisUtils;


    @PostMapping("/addDiscountTrick")
    @ApiOperation(value = "管理员新增优惠券")
    public ReturnResult<DiscountTrick> adddistrick(DiscountTrick discountTrick) {
        couponService.addDiscountTrick(discountTrick);
        redisUtils.set("discountInfo", JSON.toJSONString(discountTrick));
        log.info("优惠券信息:{}", JSON.toJSONString(discountTrick));
        return ResultBuildUtil.success(discountTrick);
    }

    @RequestPermission
    @PostMapping("/userAddDiscountTrick")
    @ApiOperation(value = "用户领取优惠券入口")
    public ReturnResult<String> userAddDiscountTrick(@RequestUser @ApiIgnore User user, Integer discountTrickId, HttpServletRequest request) {
        if (null == user || null == user.getUserId()) {
            return ResultBuildUtil.fail("1000", "请先登录");
        }
//        User user1 = userMapper1.selectByPrimaryKey(user.getUserId());
        User user1 = couponService.selectInfo(user.getUserId());
        String token = request.getHeader("token");
        redisUtils.set(token, JSON.toJSONString(user1), 24 * 60 * 60 * 3);
        boolean checkUserOnlyOne = couponService.checkUserOnlyOne(user.getUserId(), discountTrickId);
        if (checkUserOnlyOne) {
            return couponService.userAddDiscountTrick(user.getUserId(), discountTrickId);
        }
        return ResultBuildUtil.fail("1010", "此优惠券您已经领过");
    }

    @RequestPermission
    @GetMapping("/getEnableTrick")
    @ApiOperation(value = "获取所有可领取的优惠券列表")
    public ReturnResult<List<DiscountTrick>> getEnableTrick(@RequestUser @ApiIgnore User user) {
        if (null == user || null == user.getUserId()) {
            return ResultBuildUtil.fail("1000", "请先登录");
        }
        List<DiscountTrick> enableTrick = couponService.getEnableTrick();
        if (null != enableTrick && enableTrick.size() >= 0) {
            return ResultBuildUtil.success(enableTrick);
        }
        return ResultBuildUtil.fail("1010", "此优惠券您已经领过");
    }
}
